package net.easyjava.framework.web.adapter;

import com.alibaba.fastjson.JSONObject;
import net.easyjava.framework.BaseConstants;
import net.easyjava.framework.log.LogConstants;
import net.easyjava.framework.utils.EnvironmentProperties;
import net.easyjava.framework.web.security.UserSecurityBean;
import net.easyjava.framework.web.security.UserSecurityOnCookie;
import net.easyjava.framework.web.security.UserSecurityOnHead;
import net.easyjava.tools.http.request.RequestTools;
import net.easyjava.tools.lang.StringTools;
import net.easyjava.tools.model.ModelBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.NamedThreadLocal;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Map;

/**
 * Created by wxnacy on 16/7/1.
 */
public class UserSecurityAdapter extends HandlerInterceptorAdapter {
    private Logger logger = LoggerFactory.getLogger(this.getClass().getName());
    protected static final String API_SIGN_KEY = "a2dc8a390e92ab87678a5bf922fbd5dd";

    public static final String CONTENT_TYPE_JSON = "application/json; charset=UTF-8";
    public static final String CONTENT_TYPE_TEXT = "text/html;charset=UTF-8";
    public static final String PROPERTY_USER_NOSECURITY_URL = "adapter.user.no.security.url";

    private String[] noSecurityUrls;

    @Resource
    private UserSecurityOnHead userSecurityOnHead;
    @Resource
    private UserSecurityOnCookie userSecurityOnCookie;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String url = RequestTools.getRealUrl(request);
        String relativeUrl = RequestTools.getRelativeUrl(request);
        //排除不需要拦截的地址
        String urls = EnvironmentProperties.getInstance().getProperty(PROPERTY_USER_NOSECURITY_URL);
        if(!StringTools.isEmpty(urls)){
            String[] urlArr = urls.split(",");
            int index = Arrays.binarySearch(urlArr, relativeUrl);
            System.out.println("index = " + index);
            for(String u:urlArr){
                if(relativeUrl.equals(u)){
                    return true;
                }
            }
        }


        if(url.contains("login") || url.contains("register")){
            return true;
        }


        ModelBean modelBean = new ModelBean();
        UserSecurityBean userSecurityBean  = this.userSecurityOnHead.getUserSecurityBean(request);
        if(userSecurityBean != null){
            return true;
        }

        //头信息中没有从cookie中获取用户信息
        userSecurityBean  = this.userSecurityOnCookie.getUserSecurityBean(request);
        if(userSecurityBean != null){
            return true;
        }


        modelBean = new ModelBean(BaseConstants.ERROR_PUBLIC_USER_UNLOGIN);

        Map<String,String[]> params = request.getParameterMap();
        PrintWriter out = null;
        try {
            logger.info(LogConstants.API_ADAPTER_TIME_SUM, new Object[]{url, modelBean.getMessage()});
            if(params.containsKey("callback")){
                response.setContentType(CONTENT_TYPE_TEXT);
                out = response.getWriter();
                out.write(new String(params.get("callback")[0] + "("));
                out.write(JSONObject.toJSONString(modelBean));
                out.write(new String(");"));
            }else {
                response.setContentType(CONTENT_TYPE_JSON);
                out = response.getWriter();
                out.write(JSONObject.toJSONString(modelBean));
            }
            out.flush();
            out.close();
        } catch (IOException e) {
            logger.error(e.getMessage(), e.fillInStackTrace());
        }
        return false;
    }


    public String[] getNoSecurityUrls() {
        return noSecurityUrls;
    }

    public void setNoSecurityUrls(String[] noSecurityUrls) {
        this.noSecurityUrls = noSecurityUrls;
    }
}
